package com.gydz.gydzbaseframeworkboot.common.utils.result;

import com.alibaba.fastjson2.JSON;
import lombok.Data;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;

@Data
public class ResultUtils implements Serializable {

    private int code;
    private String message;
    private Object data;

    public static ResultUtils succ(Object data) {
        return succ(200, "操作成功", data);
    }

    public static ResultUtils fail(String msg) {
        return fail(400, msg, null);
    }

    public static ResultUtils succ (int code, String msg, Object data) {
        ResultUtils result = new ResultUtils();
        result.setCode(code);
        result.setMessage(msg);
        result.setData(data);
        return result;
    }

    public static ResultUtils fail (int code, String msg, Object data) {
        ResultUtils result = new ResultUtils();
        result.setCode(code);
        result.setMessage(msg);
        result.setData(data);
        return result;
    }

    public static void responseResult(HttpServletResponse httpServletResponse,ResultUtils result) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}

